import React from 'react'

export default class Paging extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      current: 1
    }
  }

  componentWillReceiveProps(props) {
    this.current = props.current
    this.setState({
      current: props.current
    })
  }

  onPageChange(event) {
    var value = $(event.target).val();
    var page = parseInt(value)
    if (value.length==0) {
      this.setState({
        current: ''
      })
    }
    else if (!isNaN(page)) {
      this.setState({
        current: page
      })
    }
  }

  handleKeyPress(event) {
    var count = this.props.count
    var limit = this.props.limit
    var total =  Math.ceil(count / limit);
    if (event.key == 'Enter') {
      var page = this.state.current
      if (page.length == 0) {
        page = 1;
      }else if (page > total || page <= 0){
        return
      }
      this.props.onPageChange(page)

    }
  }

  onPrePageClicked() {
    if (this.current > 1) {
      var pre = this.current - 1;
      this.props.onPageChange(pre)
    }
  }

  onNextPageClicked() {
    var count = this.props.count
    var limit = this.props.limit
    var total =  Math.ceil(count / limit);
    if (this.current < total) {
      var next = this.current + 1;
      this.props.onPageChange(next)
    }
  }

  onFirstPageClicked() {
    this.props.onPageChange(1)
  }

  onLastPageClicked(total) {
    this.props.onPageChange(total)
  }

  render() {
    var current = this.state.current
    var count = this.props.count
    var limit = this.props.limit
    var total =  Math.ceil(count / limit);
    return (
      <div className="pages">
        <ul className="pagination-sm pagination">
          <li className="page-pre page-top">
            <a onClick={(event)=>this.onFirstPageClicked()}> 首页</a>
          </li>
          <li className="page-pre">
            <a onClick={(event)=>this.onPrePageClicked()}> 上一页</a>
          </li>
          <li className="page-next">
            <a onClick={(event)=>this.onLastPageClicked(total)}> 尾页</a>
          </li>
          <li className="page-next">
            <a onClick={(event)=>this.onNextPageClicked()}> 下一页 </a>
          </li>
          <li>
              第
              <input type="text" value={current}
                      onChange={(event)=>this.onPageChange(event)}
                      onKeyPress = {(event)=>this.handleKeyPress(event)}/>页
              共{total}页
          </li>


        </ul>
      </div>
    )
  }

}
